#include "../collections.h"
#include <stdlib.h>

dictionary dictionary_create()
{
	dictionary self = malloc(sizeof(struct dictionary));
	self->first = NULL;

	return self;
}

void dictionary_delete(dictionary* self)
{
	dictionary_clear(*self);
	free(*self);
	*self = NULL;
}

void dictionary_clear(dictionary self)
{
	def definition = self->first;
	while (definition != NULL)
	{
		def aux = definition;
		definition = def_getlink(definition);
		def_delete(aux);
	}
	self->first = NULL;
}

int dictionary_isEmpty(dictionary self)
{
	return self->first == NULL;
}

int dictionary_count(dictionary self)
{
	int count = 0;
	def aux = self->first;
	while(aux != NULL)
	{
		aux = def_getlink(aux);
		count++;
	}
	return count;
}

int _dictionary_containsKey(dictionary self, int TKey, void* key)
{
	int containsKey = 0;
	def item;
	_dictionary_foreach(self, item, !containsKey)
		containsKey = def_isKey(item,TKey,key);

	return containsKey;
}

int _dictionary_containsValue(dictionary self, int TKey, int TValue, void* value)
{
	int containsValue = 0;
	def item;
	_dictionary_foreach(self, item, !containsValue)
		containsValue = def_isValue(item, TKey, TValue, value);

	return containsValue;
}

int _dictionary_add(dictionary self, int TKey, int TValue, void* key, void* value)
{
	if(_dictionary_containsKey(self,TKey,key))
		return -1;

	self->first = def_create(TKey, TValue, key, value, self->first);

	return 0;
}

int _dictionary_write(dictionary self, int TKey, int TValue, void* key, void* value)
{
	def item;
	int containsKey = 0;
	_dictionary_foreach(self,item,1)
	{
		containsKey = def_isKey(item, TKey, key);
		if(containsKey)
			def_writeValue(item,TKey,TValue,value);
	}

	if(!containsKey)
		self->first = def_create(TKey, TValue, key, value, self->first);

	return 0;
}

int _dictionary_ifContainsKeyDo(dictionary self, int TKey, int TValue, void* key, void* value, ifContainsKeyDo functionToDo)
{
	if(!_dictionary_containsKey(self,TKey,key))
		return -1;
	def item;
	_dictionary_foreach(self,item,1)
	{
		if(def_isKey(item, TKey, key))
		{
			functionToDo(item, TKey, TValue, value);
			break;
		}

	}

	return 0;
}

int _dictionary_remove(dictionary* self, int TKey, void* key)
{
	if(!_dictionary_containsKey(*self,TKey,key))
		return -1;
	def item;
	def prev = NULL;
	_dictionary_foreach((*self),item,1)
	{
		if(def_isKey(item, TKey, key))
		{
			if(prev != NULL)
				prev->link = def_getlink(item);
			else
				(*self)->first = def_getlink(item);
			item = def_delete(item);
			break;
		}
		prev = item;
	}

	return 0;
}







